/*
 * @Author: 杰编程 2306248989@qq.com
 * @Date: 2023-07-25 11:36:03
 * @LastEditors: 杰编程 2306248989@qq.com
 * @LastEditTime: 2023-07-25 12:03:39
 * @FilePath: /lesson20/thread.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once

#include<iostream>
#include<string>
#include<pthread.h>
#include<functional>


class thread
{
public:
    typedef enum
    {
        NEW=0,
        RUN,
        EXIT
    }ThreadStatus;

public:
    thread(int num,std::function<void(void*)> func_t,void* args)
        :_func_t(func_t)
        ,_id(0)
        ,_args(args)
        ,_status(NEW)
    {
        char buffer[64];
        snprintf(buffer,sizeof(buffer),"thread:%d ",num);
        std::string name=buffer;
        _name=move(name);
    }
    
    static void* runHelp(void* args)
    {
        thread* t=static_cast<thread*>(args);
        (*t)();
        return nullptr;
    }

    void operator()()
    {
        if(_func_t!=nullptr)_func_t(_args);;
    }

    void run()
    {
        int ret=pthread_create(&_id,nullptr,runHelp,this);
        if(ret!=0)
        {
            cout<<"create error"<<endl;
        }
        _status=RUN;
    }

    void join()
    {
        int ret=pthread_join(_id,nullptr);
        if(ret!=0)
        {
            cout<<"join errror"<<endl;
            return; 
        }
        _status=EXIT;
    }

    const std::string& threadname()
    {
        return _name;
    }
    pthread_t threadid()
    {
        return _id;
    }
    ThreadStatus status()
    {
        return _status;
    }

private:
    std::function<void(void*)> _func_t;
    std::string _name;
    pthread_t _id;
    void* _args;
    ThreadStatus _status;
};
